<?php

namespace Home\Controller;

use Think\Log;

class GoodsController extends BaseMallController
{

    function _initialize()
    {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
    }

    /**
     * @api {get} /index.php?m=Home&c=Goods&a=info 获取产品的所有信息
     */
    function info(){
        ini_set('display_errors', 'on');
        error_reporting(E_ALL);

        // 把Request信息写入日志，Powered by liuzongyang 2019/10/9 16:41
        $message = '现在正在记录Goods info商品详情，请知悉： ' . PHP_EOL;
        $message .= '接收到的Goods info Request信息如下: ' . PHP_EOL;
        $message .= print_r($_REQUEST, true);
        $logFile = C('LOG_PATH') . 'Home_goods_' . date('y_m_d') . '.log';
        Log::write($message, 'debug', '', $logFile);

        if (I('request.barcode')) {
            $res = M('goods_spec')->where(array('barcode' => I('request.barcode')))->find();
            if (!$res) {
                render('10001', '商品不存在');
            }
            $id = $res['goods_id'];
        } else if (I('request.random_str')) {
            $id = get_decrypt(I('request.random_str'));
        } else if ('request.id') {
            $id = I('request.id');
            if (empty($id)) {
                render('10001', '缺少参数');
            }
        }
        /* 商品信息 */
        $goods = D('goods')->get_info($id);
        //判断是否为已上架心愿单
        $res_activity = M('wish_activity')->order('activity_id desc')->where(array('start_time'=>array('elt',time()),'end_time'=>array('egt',time())))->find();
        $res_wish_goods = M('wish_goods')->field('goods_id')->where(array('activity_id'=>$res_activity['activity_id']))->select();
        $res_wish_goods_ids = array_column($res_wish_goods,'goods_id');
        if(in_array($goods['goods_id'],$res_wish_goods_ids) && $goods['wish_close'] == 1){
            $goods['wish_close'] = '1';
        }else{
            $goods['wish_close'] = '0';
        }

        // 在这里把查询到的goods信息返回给用户
        $message = '商品基本详情查询完毕，将要发送给用户的Goods info Response信息如下: ' . PHP_EOL;
        $message .= print_r($goods, true);
        Log::write($message, 'debug', '', $logFile);

        $preg = '/src="(.*?)"/';
        preg_match_all($preg, $goods['description'], $matchArr);
        $goods['description'] = str_replace("./data", C('SITE_URL') . '/data', $goods['description']);
        $description_array = array();
        if ($matchArr[1]) {
            foreach ($matchArr[1] as $k => $v) {
                $temp1 = str_replace("./data", 'data', $v);
                $temp2 = str_replace("store_2", 'store_2_old', $temp1);
                $temp3 = str_replace("./data", C('SITE_URL') . '/data', $v);
                $size = getimagesize($temp3);
                $description_array[] = array(
                    'url' => $temp1,
                    'url_detail' => $temp2,
                    'width' => $size[0] ? $size[0] : 600,
                    'height' => $size[1] ? $size[1] : 600,
                );

            }
        }
        $goods['build'] = $description_array;
        $goods['wish_price'] = C('wish_price');
        if (!$_POST['user_id']) {
            $goods['collectAndWish'] = false;
        } else {
            $condc['item_id'] = $id;
            $condc['user_id'] = $_POST['user_id'];
            $collect = M('collect')->where($condc)->find();
            $condw['goods_id'] = $id;
            $condw['user_id'] = $_POST['user_id'];
            $wish = M('wish')->where($condw)->find();
            if ($collect || $wish) {
                $goods['collectAndWish'] = true;
            } else {
                $goods['collectAndWish'] = false;
            }
        }
        $goods['share_str'] = $goods['goods_name'] . '￥' . set_encrypt($id) . '￥';
        $goods['share_title'] = '商品分享';
        $goods['customer_url'] = C('SITE_URL').'/index.php?app=goods&id='.$id;
        $goods['share_url'] = C('SITE_URL').'/mobile/index.php?app=qrcode&act=download';
//        $goods['share_url'] = C('SITE_URL').'/mobile/index.php?app=qrcode&act=detail';

        if (!$goods || $goods['if_show'] == 0 || $goods['closed'] == 1 || $goods['state'] != 1) {
            render('10300', '此商品不存在');
        }
        $goods['tags'] = $goods['tags'] ? explode(',', trim($goods['tags'], ',')) : array();

        /* 打折促销相关信息 BEGIN */
        $Promotion_mod = M('promotion');
        $promotion = $Promotion_mod->where("start_time<=" . time() . " AND end_time>=" . time() . " AND goods_id=" . $goods['goods_id'])->find();
        //材质
        //产地
        $res_country = M('country_info')->where(array('id' => $goods['country_id']))->find();
        $data_m[0]['title'] = '商品名称';
        $data_m[1]['title'] = '产地';
        $data_m[2]['title'] = '材质';
        $data_m[3]['title'] = '品牌';
        $data_m[4]['title'] = '国际码';
        $data_m[0]['content'] = $goods['goods_name'] ? $goods['goods_name'] : '无';
        $data_m[1]['content'] = $res_country['cn_name'] ? $res_country['cn_name'] : '无';
        $data_m[2]['content'] = $goods['material'] ? $goods['material'] : '无';
        $data_m[3]['content'] = $goods['brand'] ? $goods['brand'] : '无';
        if ($promotion) {
            $i = $is_pro = 0;
            foreach ($goods['_specs'] as $spec) {
                $spec_price = unserialize($promotion['spec_price']);
                if (isset($spec_price[$spec['spec_id']]['pro_type'])) {
                    if ($spec_price[$spec['spec_id']]['pro_type'] == 'price') {
                        if ($spec['price'] > $spec_price[$spec['spec_id']]['price']) {
                            $pro_price = round($spec['price'] - $spec_price[$spec['spec_id']]['price'], 2);
                            $is_pro = 1;
                        } else {
                            $pro_price = NULL; // 考虑设置了促销后，再给该商品添加规格的情况，那么一律给新增的规格设置促销价为NULL
                            $is_pro = 0;
                        }
                    } else {
                        $pro_price = round($spec['price'] * $spec_price[$spec['spec_id']]['price'] / 10, 2);
                        $is_pro = 1;
                    }
                } else {
                    $pro_price = NULL; // 考虑设置了促销后，再给该商品添加规格的情况，那么一律给新增的规格设置促销价为NULL
                    $is_pro = 0;
                }
                $goods['_specs'][$i++] += array('pro_price' => $pro_price, 'is_pro' => $is_pro);
            }

            $goods['lefttime'] = $this->lefttime($promotion['end_time']);

            $goods += $promotion;
        }
        /* 打折促销相关信息 END */

        $data['goods'] = $goods;
        /* 店铺信息 */
        if (!$goods['store_id']) {
            render('10302', '商品中未包含店铺ID');
        }
        $data['store'] = D('store')->get_info($goods['store_id']);

        //显示产品会员等级价格
        if ($data['goods']['if_open'] && $this->_user_id) {
            $member = D('member')->get_grade_info($this->_user_id);
            $data['goods']['grade_name'] = $member['grade_name'];
            $discount = D('gradegoods')->get_user_discount($this->_user_id, $id);
            foreach ($data['goods']['_specs'] as $key => $val) {
                $data['goods']['_specs'][$key]['member_price'] = $val['price'] * $discount;
                $data['goods']['_specs'][$key]['discount'] = $discount;
            }
        } else {

            $data['goods']['if_open'] = 0;
        }
        /* 商品的自由搭配 */
        $mix_mod = M('Mix');
        $mix_list = D('Mix')->relation(true)->alias('mix')->join('LEFT JOIN ' . C('DB_PREFIX') . 'mix_goods mix_goods ON mix_goods.mix_id=mix.mix_id ')->where('nav_goods_id=' . $data['goods']['goods_id'])->order('mix.mix_id asc,mix_goods.sort_order asc')->find();
        if ($mix_list) {
            $mix_items = array();
            //自由搭配分类
            $mix_cates = array();
            foreach ($mix_list['Goods'] as $key => $val) {
                //获取最优价格
                $spec_info = M('goods_spec')
                    ->field('g.store_id, g.if_open, g.goods_id, g.goods_name, g.spec_name_1, g.spec_name_2, g.spec_name_3, g.spec_name_4, g.default_image, gs.spec_id, gs.spec_1, gs.spec_2, gs.spec_3, gs.spec_4, gs.stock, gs.price')
                    ->alias('gs')
                    ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods g ON g.goods_id = gs.goods_id')
                    ->where('spec_id=' . $val['default_spec'])
                    ->find();
                $spec_info = D('Cart')->get_spec_price($spec_info, $this->_user_id);
                $mix_list['Goods'][$key]['price'] = $spec_info['price'];
                $mix_items[] = $mix_list['Goods'][$key];
                if (!array_key_exists($val['cate_id'], $mix_cates)) {
                    $cate_name_array = explode("\t", $val['cate_name']);
                    if ($cate_name_array) {
                        $cate_name = end($cate_name_array);
                        $mix_cates[$val['cate_id']] = $cate_name;
                    }
                }
            }
            unset($mix_list['Goods']);
            $mix_info = $mix_list;
            $data['mix_cates'] = $mix_cates;
            $data['mix_list'] = $mix_items;
            $data['mix_info'] = $mix_info;
        }
        //商品属性
        $goods_pvs = M('GoodsPvs')->where('goods_id=' . $id)->find(); // 取出该商品的属性字符串
        $goods_pvs_str = $goods_pvs['pvs'];
        $props = array();
        if (!empty($goods_pvs_str)) {
            $goods_pvs_arr = explode(';', $goods_pvs_str); //  分割成数组
            foreach ($goods_pvs_arr as $pv) {
                if ($pv) {
                    $pv_arr = explode(':', $pv);
                    $prop = M('GoodsProp')->where('pid=' . $pv_arr[0] . ' AND status=1')->find();
                    if ($prop) {
                        $prop_value = M('GoodsPropValue')->where('pid=' . $pv_arr[0] . ' AND vid=' . $pv_arr[1] . ' AND status=1')->find();
                        if ($prop_value) {
                            $props[] = array('name' => $prop['name'], 'value' => $prop_value['prop_value']);
                        }
                    }
                }
            }
        }
//      lichen 2019/5/21 start
        //商品上层规格分类
        $spec = array();
        $_spec = array();
        $goods['_specs'] = M('goods_spec')->field('ecm_goods_spec.*,ecm_size_order.size_order,ecm_storestock.arrival_time,ecm_goods_spec.price * '.$goods['discount'].' as dis_price')
            ->join('left join ecm_size_order on ecm_goods_spec.spec_2 = ecm_size_order.size_name')
            ->join('left join ecm_storestock on ecm_goods_spec.spec_3value = ecm_storestock.storestock_id')
            ->order('ecm_size_order.size_order')
//            ->order('ecm_size_order.size_order,FIELD(ecm_goods_spec.spec_3,"境内仓","香港直邮仓")')
            ->where(array('goods_id' => $id))
            ->select();
        if (!$goods['_specs'][0]['size_order'] && $goods['_specs']) {
            $last_names = array_column($goods['_specs'], 'spec_2');
            array_multisort($last_names, SORT_ASC, $goods['_specs']);
        }
//        $goods['_specs'] = M('goods_spec')->where(array('goods_id'=>$id))->select();
        $data_sku = array();
        if ($goods['_specs'] && is_array($goods['_specs'])) {
//            if ($goods['spec_qty'] > 0 && $goods['_specs'] && is_array($goods['_specs'])) {

            foreach ($goods['_specs'] as $k => $v) {

                if ($v['spec_1'] && $v['spec_1value']) {
                    $spec['spec_1']['k'] = $goods['spec_name_1'];
                    if (!in_array($v['spec_1value'], $spec['spec_1']['v']) && !in_array($v['spec_1'], $spec['spec_1']['c'])) {
                        $spec['spec_1']['v'][] = $v['spec_1value'];
                        $spec['spec_1']['c'][] = $v['spec_1'];
                    }
                }

                if (strlen($v['spec_2'])) {
                    $spec['spec_2']['k'] = $goods['spec_name_2'];
                    if (!in_array($v['spec_2'], $spec['spec_2']['v'])) {
                        $spec['spec_2']['v'][] = $v['spec_2'];
                    }
                }
                if ($v['spec_3']) {
                    $spec['spec_3']['k'] = $goods['spec_name_3'];
                    if (!in_array($v['spec_3'], $spec['spec_3']['v'])) {
                        $spec['spec_3']['v'][] = $v['spec_3'];
                        $spec['spec_3']['s'][] = $v['arrival_time'];
                    }
                }
                if ($v['spec_4']) {
                    $spec['spec_4']['k'] = $goods['spec_name_4'];
                    if (!in_array($v['spec_4'], $spec['spec_4']['v'])) {
                        $spec['spec_4']['v'][] = $v['spec_4'];
                    }
                }
                $data_sku[] = substr($v['sku'], 0, strrpos($v['sku'], '|'));

            }
            $data_sku = array_unique($data_sku);
            $data_m[4]['content'] = implode("\n", $data_sku);
            $_spec = array_values($spec);
            $sort_rule = array(
                0 => '境内仓',
                1 => '天津保税仓',
                2 => '香港直邮仓',
                3 => '海外直邮仓'
            );
            for ($i = 0; $i < count($sort_rule); $i++) {
                for ($j = 0; $j < count($_spec[2]['v']); $j++) {
                    if ($_spec[2]['v'][$j] == $sort_rule[$i]) {
                        $c[$i] = $_spec[2]['v'][$j];
                        $d[$i] = $_spec[2]['s'][$j];
                    }
                }
            }
            $_spec[2]['v'] = array_values($c);
            $_spec[2]['s'] = array_values($d);
//            $_spec[2] = $temp_arr;
            $data['goods']['_spec'] = $_spec;
            $priceNewArr = array();
            if ($_POST['token']) {
                $res_token = M('app_token')->where(array('token' => $_POST['token']))->find();
                $res_user = M('member')->where(array('user_id' => $res_token['user_id']))->find();
            }
            foreach ($data['goods']['_specs'] as $k => $v) {
                $temp = $data['goods']['_specs'][$k]['spec_1'];
                $data['goods']['_specs'][$k]['spec_1'] = $data['goods']['_specs'][$k]['spec_1value'];
                $data['goods']['_specs'][$k]['spec_1value'] = $temp;

                $priceNewArr[$k]['price'] = $v['price'];
                $priceNewArr[$k]['discount_price'] = $v['discount_price'];
                $data['goods']['_specs'][$k]['wish_price'] = (string)($goods['discount'] * $v['price']);
            }
        }

        /**组合后的规格价格和当前商品价格进行排序*/
//            $arr[0]['price'] = $data['goods']['_specs']['price'];
//            array_walk($arr,function($item) use (&$priceNewArr) {
//                array_unshift($priceNewArr, $item);
//            });
        /**获得规格和普通价格的比较对应的大小值*/
        $res_cost = array_sort($priceNewArr, 'price');
        /**区间价格*/
        $data['goods']['first_cost_price'] = $res_cost['first'];
        $data['goods']['end_cost_price'] = $res_cost['end'];
        /**获得规格和折扣价格的比较对应的大小值*/
        $res_discount = array_sort($priceNewArr, 'discount_price');
        /**区间价格*/
        $data['goods']['first_discount_price'] = $res_discount['first'];
        $data['goods']['end_discount_price'] = $res_discount['end'];
        //判断价格
        if ($data['goods']['sto_id'] && $_POST['token'] && $res_user) {
            $res_store_goods = M('store')->where(array('store_id' => $data['goods']['sto_id']))->find();
            $res_store_user = M('store')->where(array('store_id' => $res_user['s_id']))->find();
            $res_region_goods = M('region')->where(array('region_id' => $res_store_goods['region_id']))->find();
            $res_region_user = M('region')->where(array('region_id' => $res_store_user['region_id']))->find();
            if ($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']) {
                //显示优惠价
                $data['goods']['first_price'] = ($res_discount['first'] < $res_cost['first']) && $res_cost['first'] != '0.00' && $res_discount['first'] != '0.00' ? $res_discount['first'] : $res_cost['first'];
                $data['goods']['end_price'] = ($res_discount['end'] < $res_cost['end']) && $res_cost['end'] != 0.00 && $res_discount['end'] != '0.00' ? $res_discount['end'] : $res_cost['end'];

            } else {
                //显示普通价
                $data['goods']['first_price'] = $res_cost['first'];
                $data['goods']['end_price'] = $res_cost['end'];
                $data['goods']['ico'] = '';
            }
        } else if (strlen($data['goods']['sto_id']) && $data['goods']['sto_id'] == '0') {
            //显示优惠价
            $data['goods']['first_price'] = ($res_discount['first'] < $res_cost['first']) && $res_cost['first'] != '0.00' && $res_discount['first'] != '0.00' ? $res_discount['first'] : $res_cost['first'];
            $data['goods']['end_price'] = ($res_discount['end'] < $res_cost['end']) && $res_cost['end']  != '0.00' && $res_discount['end'] != '0.00' ? $res_discount['end'] : $res_cost['end'];
        } else {
            //显示普通价
            $data['goods']['first_price'] = $res_cost['first'];
            $data['goods']['end_price'] = $res_cost['end'];
            $data['goods']['ico'] = '';
        }


        //删除库存为0的规格
        foreach ($data['goods']['_specs'] as $key => $value) {
            if ($value['stock'] < 0 || $value['stock'] == 0) {
                unset($data['goods']['_specs'][$key]);
                continue;
            }

            if ($value['sto_id'] && $_POST['token'] && $res_user) {
                $res_store_goods = M('store')->where(array('store_id' => $value['sto_id']))->find();
                $res_store_user = M('store')->where(array('store_id' => $res_user['s_id']))->find();
                $res_region_goods = M('region')->where(array('region_id' => $res_store_goods['region_id']))->find();
                $res_region_user = M('region')->where(array('region_id' => $res_store_user['region_id']))->find();
                if(($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']) && $value['discount_price'] != '0.00' && $value['price'] != '0.00'){
                    $data['goods']['_specs'][$key]['price'] = $value['discount_price'] < $value['price'] ? $value['discount_price'] : $value['price'];
                    $data['goods']['_specs'][$key]['tax_price'] = $value['discount_price'] < $value['price'] ? $value['tax_discount_price'] : $value['tax_price'];
                }else{
                    $data['goods']['_specs'][$key]['price'] = $value['price'];
                }
            } else if (strlen($value['sto_id']) && $value['sto_id'] == '0') {
                //显示优惠价
                if($value['discount_price'] != '0.00' && $value['price'] != '0.00'){
                    $data['goods']['_specs'][$key]['price'] = $value['discount_price'] < $value['price'] ? $value['discount_price'] : $value['price'];
                    $data['goods']['_specs'][$key]['tax_price'] = $value['discount_price'] < $value['price'] ? $value['tax_discount_price'] : $value['tax_price'];
                }else{
                    $data['goods']['_specs'][$key]['price'] = $value['price'];
                }
            } else {
                //显示普通价
                $data['goods']['_specs'][$key]['price'] = $value['price'];
            }

        }
        $data['goods']['_specs'] = array_values($data['goods']['_specs']);
        $data['goods']['tax_description'] = C('TAX_DESCRIPTION');
//      lichen 2019/5/21 end
        $data['goods']['props'] = $props;
        if(!$goods['spec_qty'] > 0 || !$goods['_specs'] || !is_array($goods['_specs'])){
            $data['goods']['_specs'][0]['spec_1value'] = $data['goods']['default_image'];
        }
        $data['goods']['message'] = $data_m;

        // 这里显示的是最终将要给用户返回的数据
        $message = '商品基本详情处理完毕，将要发送给用户最终的Goods info Response信息如下: ' . PHP_EOL;
        $message .= print_r($data, true);
        Log::write($message, 'debug', '', $logFile);

        render('10000', '成功', $data);

    }

        /**
         * @api {get} /index.php?m=Home&c=Goods&a=detail 显示商品的详情信息
         *
         * @apiName 显示商品的详情信息
         * @apiGroup All
         * @apiVersion 0.1.0
         * @apiDescription 显示商品的详情信息
         *
         *
         *
         */
        function detail()
        {
            $id = I('request.id');
            if (empty($id)) {
                render('10001', '缺少参数');
            }

            /* 商品信息 */
            $goods = D('goods')->get_info($id);
            if (!$goods || $goods['if_show'] == 0 || $goods['closed'] == 1 || $goods['state'] != 1) {
                render('10300', '此商品不存在');
            }
            $goods['description'] = str_replace("./data", C('SITE_URL') . '/data', $goods['description']);
            $this->assign('goods', $goods);
            $this->display();
        }


        function lefttime($time)
        {
            $lefttime = $time - time();
            if (empty($time) || $lefttime <= 0) {
                return array();
            }
            $d = intval($lefttime / 86400);
            $lefttime -= $d * 86400;
            $h = intval($lefttime / 3600);
            $lefttime -= $h * 3600;
            $m = intval($lefttime / 60);
            $lefttime -= $m * 60;
            $s = $lefttime;
            return array(
                "d" => $d,
                "h" => $h,
                "m" => $m,
                "s" => $s
            );
        }

        /**
         * @api {get} /index.php?m=Home&c=Goods&a=comments 获取产品的评价
         */
        function comments()
        {
            $goods_id = I('request.id');
            if (empty($goods_id)) {
                render('10001', '缺少参数');
            }
            import("Org.Com.Evaluation");
            $evaluation = new \Org\Com\Evaluation;

            $data = array();

            $conditions = "goods_id = '$goods_id' AND evaluation_status = '1'";
            if (in_array(I('request.evalscore'), array('1', '2', '3'))) {
                $conditions .= ' AND evaluation=' . $_GET['evalscore'];
            }
            if (I('request.havecomment') == '1') {
                $conditions .= ' AND comment !=""';
            }

            $comments = M('OrderGoods')->alias('ordergoods')
                ->field('buyer_id, buyer_name, anonymous, evaluation_time, comment, evaluation')
                ->where($conditions)->join('LEFT JOIN ' . C('DB_PREFIX') . 'order order_alias ON order_alias.order_id=ordergoods.order_id')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->order('evaluation_time desc')
                ->select();

            //获取买家的信誉
            if (!empty($comments)) {
                foreach ($comments as $key => $value) {
                    $data = $evaluation->get_buyer_evaluation($value['buyer_id']);
                    $comments[$key]['buyer_credit_value'] = $data['buyer_credit_value'];
                    $comments[$key]['buyer_credit_image'] = $data['buyer_credit_image'];
                    $comments[$key]['buyer_praise_rate'] = $data['buyer_praise_rate'];
                    $comments[$key]['evaluation_time'] = date('Y-m-d H:i:s', $value['evaluation_time']);
                }
            }
            unset($data['buyer_credit_value']);
            unset($data['buyer_credit_image']);
            unset($data['buyer_praise_rate']);
            $data['comments'] = $comments;
            render('10000', '', $data);
        }

        function info_test(){
                ini_set('display_errors', 'on');
                error_reporting(E_ALL);

                // 把Request信息写入日志，Powered by liuzongyang 2019/10/9 16:41
                $message = '现在正在记录Goods info商品详情，请知悉： ' . PHP_EOL;
                $message .= '接收到的Goods info Request信息如下: ' . PHP_EOL;
                $message .= print_r($_REQUEST, true);
                $logFile = C('LOG_PATH') . 'Home_goods_' . date('y_m_d') . '.log';
                Log::write($message, 'debug', '', $logFile);

                if (I('request.barcode')) {
                    $res = M('goods_spec')->where(array('barcode' => I('request.barcode')))->find();
                    if (!$res) {
                        render('10001', '商品不存在');
                    }
                    $id = $res['goods_id'];
                } else if (I('request.random_str')) {
                    $id = get_decrypt(I('request.random_str'));
                } else if ('request.id') {
                    $id = I('request.id');
                    if (empty($id)) {
                        render('10001', '缺少参数');
                    }
                }
                /* 商品信息 */
                $goods = D('goods')->get_info_test($id);

                // 在这里把查询到的goods信息返回给用户
                $message = '商品基本详情查询完毕，将要发送给用户的Goods info Response信息如下: ' . PHP_EOL;
                $message .= print_r($goods, true);
                Log::write($message, 'debug', '', $logFile);

                $preg = '/src="(.*?)"/';
                preg_match_all($preg, $goods['description'], $matchArr);
                $goods['description'] = str_replace("./data", C('SITE_URL') . '/data', $goods['description']);
                $description_array = array();
                if ($matchArr[1]) {
                    foreach ($matchArr[1] as $k => $v) {
                        $temp1 = str_replace("./data", 'data', $v);
                        $temp2 = str_replace("store_2", 'store_2_old', $temp1);
                        $temp3 = str_replace("./data", C('SITE_URL') . '/data', $v);
                        $size = getimagesize($temp3);
                        $description_array[] = array(
                            'url' => $temp1,
                            'url_detail' => $temp2,
                            'width' => $size[0],
                            'height' => $size[1],
                        );

                    }
                }
                $goods['build'] = $description_array;
                $goods['wish_price'] = C('wish_price');
                if (!$_POST['user_id']) {
                    $goods['collectAndWish'] = false;
                } else {
                    $condc['item_id'] = $id;
                    $condc['user_id'] = $_POST['user_id'];
                    $collect = M('collect')->where($condc)->find();
                    $condw['goods_id'] = $id;
                    $condw['user_id'] = $_POST['user_id'];
                    $wish = M('wish')->where($condw)->find();
                    if ($collect || $wish) {
                        $goods['collectAndWish'] = true;
                    } else {
                        $goods['collectAndWish'] = false;
                    }
                }
                $goods['share_str'] = $goods['goods_name'] . '￥' . set_encrypt($id) . '￥';
                $goods['share_title'] = '商品分享';
                if (!$goods || $goods['if_show'] == 0 || $goods['closed'] == 1 || $goods['state'] != 1) {
                    render('10300', '此商品不存在');
                }
                $goods['tags'] = $goods['tags'] ? explode(',', trim($goods['tags'], ',')) : array();

                /* 打折促销相关信息 BEGIN */
                $Promotion_mod = M('promotion');
                $promotion = $Promotion_mod->where("start_time<=" . time() . " AND end_time>=" . time() . " AND goods_id=" . $goods['goods_id'])->find();
                //材质
                //产地
                $res_country = M('country_info')->where(array('id' => $goods['country_id']))->find();
                $data_m[0]['title'] = '商品名称';
                $data_m[1]['title'] = '产地';
                $data_m[2]['title'] = '材质';
                $data_m[3]['title'] = '品牌';
                $data_m[4]['title'] = '国际码';
                $data_m[0]['content'] = $goods['goods_name'] ? $goods['goods_name'] : '无';
                $data_m[1]['content'] = $res_country['cn_name'] ? $res_country['cn_name'] : '无';
                $data_m[2]['content'] = $goods['material'] ? $goods['material'] : '无';
                $data_m[3]['content'] = $goods['brand'] ? $goods['brand'] : '无';
                if ($promotion) {
                    $i = $is_pro = 0;
                    foreach ($goods['_specs'] as $spec) {
                        $spec_price = unserialize($promotion['spec_price']);
                        if (isset($spec_price[$spec['spec_id']]['pro_type'])) {
                            if ($spec_price[$spec['spec_id']]['pro_type'] == 'price') {
                                if ($spec['price'] > $spec_price[$spec['spec_id']]['price']) {
                                    $pro_price = round($spec['price'] - $spec_price[$spec['spec_id']]['price'], 2);
                                    $is_pro = 1;
                                } else {
                                    $pro_price = NULL; // 考虑设置了促销后，再给该商品添加规格的情况，那么一律给新增的规格设置促销价为NULL
                                    $is_pro = 0;
                                }
                            } else {
                                $pro_price = round($spec['price'] * $spec_price[$spec['spec_id']]['price'] / 10, 2);
                                $is_pro = 1;
                            }
                        } else {
                            $pro_price = NULL; // 考虑设置了促销后，再给该商品添加规格的情况，那么一律给新增的规格设置促销价为NULL
                            $is_pro = 0;
                        }
                        $goods['_specs'][$i++] += array('pro_price' => $pro_price, 'is_pro' => $is_pro);
                    }

                    $goods['lefttime'] = $this->lefttime($promotion['end_time']);

                    $goods += $promotion;
                }
                /* 打折促销相关信息 END */

                $data['goods'] = $goods;
                /* 店铺信息 */
                if (!$goods['store_id']) {
                    render('10302', '商品中未包含店铺ID');
                }
                $data['store'] = D('store')->get_info($goods['store_id']);

                //显示产品会员等级价格
                if ($data['goods']['if_open'] && $this->_user_id) {
                    $member = D('member')->get_grade_info($this->_user_id);
                    $data['goods']['grade_name'] = $member['grade_name'];
                    $discount = D('gradegoods')->get_user_discount($this->_user_id, $id);
                    foreach ($data['goods']['_specs'] as $key => $val) {
                        $data['goods']['_specs'][$key]['member_price'] = $val['price'] * $discount;
                        $data['goods']['_specs'][$key]['discount'] = $discount;
                    }
                } else {

                    $data['goods']['if_open'] = 0;
                }
                /* 商品的自由搭配 */
                $mix_mod = M('Mix');
                $mix_list = D('Mix')->relation(true)->alias('mix')->join('LEFT JOIN ' . C('DB_PREFIX') . 'mix_goods mix_goods ON mix_goods.mix_id=mix.mix_id ')->where('nav_goods_id=' . $data['goods']['goods_id'])->order('mix.mix_id asc,mix_goods.sort_order asc')->find();
                if ($mix_list) {
                    $mix_items = array();
                    //自由搭配分类
                    $mix_cates = array();
                    foreach ($mix_list['Goods'] as $key => $val) {
                        //获取最优价格
                        $spec_info = M('goods_spec')
                            ->field('g.store_id, g.if_open, g.goods_id, g.goods_name, g.spec_name_1, g.spec_name_2, g.spec_name_3, g.spec_name_4, g.default_image, gs.spec_id, gs.spec_1, gs.spec_2, gs.spec_3, gs.spec_4, gs.stock, gs.price')
                            ->alias('gs')
                            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods g ON g.goods_id = gs.goods_id')
                            ->where('spec_id=' . $val['default_spec'])
                            ->find();
                        $spec_info = D('Cart')->get_spec_price($spec_info, $this->_user_id);
                        $mix_list['Goods'][$key]['price'] = $spec_info['price'];
                        $mix_items[] = $mix_list['Goods'][$key];
                        if (!array_key_exists($val['cate_id'], $mix_cates)) {
                            $cate_name_array = explode("\t", $val['cate_name']);
                            if ($cate_name_array) {
                                $cate_name = end($cate_name_array);
                                $mix_cates[$val['cate_id']] = $cate_name;
                            }
                        }
                    }
                    unset($mix_list['Goods']);
                    $mix_info = $mix_list;
                    $data['mix_cates'] = $mix_cates;
                    $data['mix_list'] = $mix_items;
                    $data['mix_info'] = $mix_info;
                }
                //商品属性
                $goods_pvs = M('GoodsPvs')->where('goods_id=' . $id)->find(); // 取出该商品的属性字符串
                $goods_pvs_str = $goods_pvs['pvs'];
                $props = array();
                if (!empty($goods_pvs_str)) {
                    $goods_pvs_arr = explode(';', $goods_pvs_str); //  分割成数组
                    foreach ($goods_pvs_arr as $pv) {
                        if ($pv) {
                            $pv_arr = explode(':', $pv);
                            $prop = M('GoodsProp')->where('pid=' . $pv_arr[0] . ' AND status=1')->find();
                            if ($prop) {
                                $prop_value = M('GoodsPropValue')->where('pid=' . $pv_arr[0] . ' AND vid=' . $pv_arr[1] . ' AND status=1')->find();
                                if ($prop_value) {
                                    $props[] = array('name' => $prop['name'], 'value' => $prop_value['prop_value']);
                                }
                            }
                        }
                    }
                }
//      lichen 2019/5/21 start
                //商品上层规格分类
                $spec = array();
                $_spec = array();
                $goods['_specs'] = M('goods_spec')->field('ecm_goods_spec.*,ecm_size_order.size_order,ecm_storestock.arrival_time')
                    ->join('left join ecm_size_order on ecm_goods_spec.spec_2 = ecm_size_order.size_name')
                    ->join('left join ecm_storestock on ecm_goods_spec.spec_3value = ecm_storestock.storestock_id')
                    ->order('ecm_size_order.size_order')
//            ->order('ecm_size_order.size_order,FIELD(ecm_goods_spec.spec_3,"境内仓","香港直邮仓")')
                    ->where(array('goods_id' => $id))
                    ->select();
                if (!$goods['_specs'][0]['size_order'] && $goods['_specs']) {
                    $last_names = array_column($goods['_specs'], 'spec_2');
                    array_multisort($last_names, SORT_ASC, $goods['_specs']);
                }
//        $goods['_specs'] = M('goods_spec')->where(array('goods_id'=>$id))->select();
                $data_sku = array();
                if ($goods['_specs'] && is_array($goods['_specs'])) {
//            if ($goods['spec_qty'] > 0 && $goods['_specs'] && is_array($goods['_specs'])) {

                    foreach ($goods['_specs'] as $k => $v) {

                        if ($v['spec_1'] && $v['spec_1value']) {
                            $spec['spec_1']['k'] = $goods['spec_name_1'];
                            if (!in_array($v['spec_1value'], $spec['spec_1']['v']) && !in_array($v['spec_1'], $spec['spec_1']['c'])) {
                                $spec['spec_1']['v'][] = $v['spec_1value'];
                                $spec['spec_1']['c'][] = $v['spec_1'];
                            }
                        }

                        if ($v['spec_2']) {
                            $spec['spec_2']['k'] = $goods['spec_name_2'];
                            if (!in_array($v['spec_2'], $spec['spec_2']['v'])) {
                                $spec['spec_2']['v'][] = $v['spec_2'];
                            }
                        }
                        if ($v['spec_3']) {
                            $spec['spec_3']['k'] = $goods['spec_name_3'];
                            if (!in_array($v['spec_3'], $spec['spec_3']['v'])) {
                                $spec['spec_3']['v'][] = $v['spec_3'];
                                $spec['spec_3']['s'][] = $v['arrival_time'];
                            }
                        }
                        if ($v['spec_4']) {
                            $spec['spec_4']['k'] = $goods['spec_name_4'];
                            if (!in_array($v['spec_4'], $spec['spec_4']['v'])) {
                                $spec['spec_4']['v'][] = $v['spec_4'];
                            }
                        }
                        $data_sku[] = substr($v['sku'], 0, strrpos($v['sku'], '|'));

                    }
                    $data_sku = array_unique($data_sku);
                    $data_m[4]['content'] = implode("\n", $data_sku);
                    $_spec = array_values($spec);
                    $sort_rule = array(
                        0 => '境内仓',
                        1 => '天津保税仓',
                        2 => '香港直邮仓',
                        3 => '海外直邮仓'
                    );
                    for ($i = 0; $i < count($sort_rule); $i++) {
                        for ($j = 0; $j < count($_spec[2]['v']); $j++) {
                            if ($_spec[2]['v'][$j] == $sort_rule[$i]) {
                                $c[$i] = $_spec[2]['v'][$j];
                                $d[$i] = $_spec[2]['s'][$j];
                            }
                        }
                    }
                    $_spec[2]['v'] = array_values($c);
                    $_spec[2]['s'] = array_values($d);
//            $_spec[2] = $temp_arr;
                    $data['goods']['_spec'] = $_spec;
                    $priceNewArr = array();
                    if ($_POST['token']) {
                        $res_token = M('app_token')->where(array('token' => $_POST['token']))->find();
                        $res_user = M('member')->where(array('user_id' => $res_token['user_id']))->find();
                    }
                    foreach ($data['goods']['_specs'] as $k => $v) {
                        $temp = $data['goods']['_specs'][$k]['spec_1'];
                        $data['goods']['_specs'][$k]['spec_1'] = $data['goods']['_specs'][$k]['spec_1value'];
                        $data['goods']['_specs'][$k]['spec_1value'] = $temp;

                        $priceNewArr[$k]['price'] = $v['price'];
                        $priceNewArr[$k]['discount_price'] = $v['discount_price'];
                    }
                }

                /**组合后的规格价格和当前商品价格进行排序*/
//            $arr[0]['price'] = $data['goods']['_specs']['price'];
//            array_walk($arr,function($item) use (&$priceNewArr) {
//                array_unshift($priceNewArr, $item);
//            });
                /**获得规格和普通价格的比较对应的大小值*/
                $res_cost = array_sort($priceNewArr, 'price');
                /**区间价格*/
                $data['goods']['first_cost_price'] = $res_cost['first'];
                $data['goods']['end_cost_price'] = $res_cost['end'];
                /**获得规格和折扣价格的比较对应的大小值*/
                $res_discount = array_sort($priceNewArr, 'discount_price');
                /**区间价格*/
                $data['goods']['first_discount_price'] = $res_discount['first'];
                $data['goods']['end_discount_price'] = $res_discount['end'];
                //判断价格
                if ($data['goods']['sto_id'] && $_POST['token'] && $res_user) {
                    $res_store_goods = M('store')->where(array('store_id' => $data['goods']['sto_id']))->find();
                    $res_store_user = M('store')->where(array('store_id' => $res_user['s_id']))->find();
                    $res_region_goods = M('region')->where(array('region_id' => $res_store_goods['region_id']))->find();
                    $res_region_user = M('region')->where(array('region_id' => $res_store_user['region_id']))->find();
                    if ($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']) {
                        //显示优惠价
                        $data['goods']['first_price'] = ($res_discount['first'] < $res_cost['first']) && $res_cost['first'] ? $res_discount['first'] : $res_cost['first'];
                        $data['goods']['end_price'] = ($res_discount['end'] < $res_cost['end']) && $res_cost['end'] ? $res_discount['end'] : $res_cost['end'];

                    } else {
                        //显示普通价
                        $data['goods']['first_price'] = $res_cost['first'];
                        $data['goods']['end_price'] = $res_cost['end'];
                        $data['goods']['ico'] = '';

                    }
                } else if (strlen($data['goods']['sto_id']) && $data['goods']['sto_id'] == '0') {
                    //显示优惠价
                    $data['goods']['first_price'] = ($res_discount['first'] < $res_cost['first']) && $res_cost['first'] ? $res_discount['first'] : $res_cost['first'];
                    $data['goods']['end_price'] = ($res_discount['end'] < $res_cost['end']) && $res_cost['end'] ? $res_discount['end'] : $res_cost['end'];
                } else {
                    //显示普通价
                    $data['goods']['first_price'] = $res_cost['first'];
                    $data['goods']['end_price'] = $res_cost['end'];
                    $data['goods']['ico'] = '';
                }


                    //删除库存为0的规格
                    foreach ($data['goods']['_specs'] as $key => $value) {
                        if ($value['stock'] < 0 || $value['stock'] == 0) {
                            unset($data['goods']['_specs'][$key]);
                            continue;
                        }

                        if ($value['sto_id'] && $_POST['token'] && $res_user) {
                            $res_store_goods = M('store')->where(array('store_id' => $value['sto_id']))->find();
                            $res_store_user = M('store')->where(array('store_id' => $res_user['s_id']))->find();
                            $res_region_goods = M('region')->where(array('region_id' => $res_store_goods['region_id']))->find();
                            $res_region_user = M('region')->where(array('region_id' => $res_store_user['region_id']))->find();
                            if(($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']) && $value['discount_price'] != '0.00' && $value['price'] != '0.00'){
                                $data['goods']['_specs'][$key]['price'] = $value['discount_price'] < $value['price'] ? $value['discount_price'] : $value['price'];
                            }else{
                                $data['goods']['_specs'][$key]['price'] = $value['price'];
                            }
                        } else if (strlen($value['sto_id']) && $value['sto_id'] == '0') {
                            //显示优惠价
                            if($value['discount_price'] != '0.00' && $value['price'] != '0.00'){
                                $data['goods']['_specs'][$key]['price'] = $value['discount_price'] < $value['price'] ? $value['discount_price'] : $value['price'];
                            }else{
                                $data['goods']['_specs'][$key]['price'] = $value['price'];
                            }
                        } else {
                            //显示普通价
                            $data['goods']['_specs'][$key]['price'] = $value['price'];
                        }

                    }
                    $data['goods']['_specs'] = array_values($data['goods']['_specs']);
                    $data['goods']['tax_description'] = C('TAX_DESCRIPTION');

//      lichen 2019/5/21 end
                    $data['goods']['props'] = $props;
                    if(!$goods['spec_qty'] > 0 || !$goods['_specs'] || !is_array($goods['_specs'])){
                        $data['goods']['_specs'][0]['spec_1value'] = $data['goods']['default_image'];
                    }
                $data['goods']['message'] = $data_m;

                // 这里显示的是最终将要给用户返回的数据
                $message = '商品基本详情处理完毕，将要发送给用户最终的Goods info Response信息如下: ' . PHP_EOL;
                $message .= print_r($data, true);
                Log::write($message, 'debug', '', $logFile);

                render('10000', '成功', $data);

            }


}
